package com.me.tags;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.lang.reflect.InvocationTargetException;
import java.util.List;

public class ForeachTag extends TagSupport {
	private List<?> items;
	private String var;
	private String index;
	private int i;

	@Override
	public int doStartTag() throws JspException {
		if (items == null || items.size() == 0){
			return SKIP_BODY;
		}
		if(index==null)index = "";

		i = 0;
		if(i<items.size()){
			pageContext.setAttribute(var, items.get(i));
			pageContext.setAttribute(index, i);
		}

		return EVAL_BODY_INCLUDE;
	}

	@Override
	public int doAfterBody() throws JspException {
		i++;
		if(i < items.size()){
			pageContext.setAttribute(var, items.get(i));
			pageContext.setAttribute(index, i);
			return EVAL_BODY_AGAIN;
		}

		return SKIP_BODY;
	}

	@Override
	public int doEndTag() throws JspException {
		return EVAL_PAGE;
	}
	public void setVar(String var) {
		this.var = var;
	}

	public void setIndex(String index){
		this.index = index;
	}
	public void setJsp_for(String jsp_for) {
		try {
			Object obj = pageContext.getRequest().getAttribute("Model");
			items = (List<?>)obj.getClass().getMethod("get" + jsp_for.substring(0,1).toUpperCase() + jsp_for.substring(1)).invoke(obj);
		} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			e.printStackTrace();
		}
	}
}
